package com.wing.product.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.common.exception.BusinessException;
import com.wing.product.dao.ProductUnitDao;
import com.wing.product.model.entity.ProductUnitInfo;
import com.wing.product.model.request.ProductUnitInfoForm;
import com.wing.product.model.response.ProductUnitInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 产品单位-ServiceImpl
 *
 * @author
 */
@Service
@Slf4j
public class ProductUnitServiceImpl extends ServiceImpl<ProductUnitDao, ProductUnitInfo> implements ProductUnitService {

    @Autowired
    private DynamicService dynamicService;

    @Override
    public int add(ProductUnitInfoForm productUnitInfoForm) {
        //校验
        ProductUnitInfo productUnitInfo = new ProductUnitInfo();
        CopyOptions copyOptions = CopyOptions.create()
                .setEditable(ProductUnitInfo.class)
                .setIgnoreError(true)
                .setIgnoreNullValue(true);
        BeanUtil.copyProperties(productUnitInfoForm, productUnitInfo, copyOptions);
        String code = getCode();
        productUnitInfo.setNo(Integer.valueOf(code));
        productUnitInfo.setCode("U" + code);

        return baseMapper.insert(productUnitInfo);
    }

    private String getCode() {
        String code = "";
        Integer maxNo = dynamicService.getMaxNo("pro_product_unit");
        if (maxNo == null) {
            maxNo = 1;
        } else {
            maxNo += 1;
        }
        for (int i = 0; i < 4 - maxNo.toString().length(); i++) {
            code += "0";
        }
        return code + maxNo.toString();
    }

    @Override
    public List<ProductUnitInfoVO> list4app(Map<String, Object> params) {
        return baseMapper.list4app(params);
    }

    @Override
    public Page<ProductUnitInfoVO> pageList4app(Page page, Map<String, Object> params) {
        List<ProductUnitInfoVO> list = baseMapper.list4app(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public ProductUnitInfoVO get4appById(Long id) {
        return baseMapper.get4appById(id);
    }

    /**
     * 查询单位并且分组
     * @return
     */
    @Override
    public List<String> getUnitByGrounp() {
        return this.baseMapper.getUnitByGrounp();
    }

    @Override
    public List<ProductUnitInfo> getUnitDisInfo() {
        return baseMapper.getUnitDisInfo();
    }
}
